<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.io.*"%> 
<%@ page import="wayden.ConnectDB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
    String INS = "INSERT INTO users (id_role,fullname,login,password,email,activated) VALUES (?,?,?,?,?,0);";
    String fullname = request.getParameter("name");
    String login = request.getParameter("login");
    String password = request.getParameter("password");
    String email = request.getParameter("email");
    String select = "select * from users order by id desc";
    String insert = "insert into profile (id_user,about,logo) values (?,?,?)";
    String check = "select * from users where login = ?";
    Connection connection = null;
	ConnectDB connectDB = new ConnectDB(); 
    
    PreparedStatement pstatement = null;
    if (fullname != null && login != null && password != null
		    && email != null) {
		if (!(fullname.isEmpty() || login.isEmpty()
			|| password.isEmpty() || email.isEmpty())) {

		    
			
			
			try {
			    connection = connectDB.Connect();
			    
			    Statement st = connection.createStatement();
			    PreparedStatement ps = connection.prepareStatement(check);
			    ps.setString(1, login);
			    ps.execute();
			    ResultSet rs = ps.getResultSet();
			    rs.next();
			    int isRegistered = rs.getRow();
			    
			    if (isRegistered == 0) {
			    ps = connection.prepareStatement(INS);
			    ps.setInt(1, 1);
			    ps.setString(2, fullname);
			    ps.setString(3, login);
			    ps.setString(4, password);
			    ps.setString(5, email);
			    int count = ps.executeUpdate();
			    if(count>0)
			    {
			    %>
<h1 align="center">Congratulation!!! You have been registered</h1>
<h2 align="center"><a href="login.jsp">Login In</a></h2>
<%	
	st.executeQuery(select);
	rs = st.getResultSet();
	rs.next();
	String id = rs.getString(1);

	
	ps = connection.prepareStatement(insert);
	ps.setString(1, id);
	ps.setString(2, "");
	ps.setString(3, "");
	
	ps.execute();
	
			    }
			    }
			    else {%>

			<center><h2>Sorry, but user with this name already registered.</h2></center>			

		<%}
			    
			    connection.close();
			} catch (SQLException ex) {
			    ex.printStackTrace();
			    out.println("Unable to connect to batabase.");
			}


		}
		
    }
%>


</body>
</html>